# -*- coding:utf-8 -*-
# coding=utf-8

import sys
import importlib
import os
import codecs
import shutil
import random
import re
import json
import struct
import time


importlib.reload(sys)

'''
DEFAULT_PCM_DIR = "./default_tones/"
PCM_DIR = "./tones/"
WAV_PCM_DIR = "./wav_tones/"
PCM_BASE_ADDR = 0x00	#必须是4K的整数倍
PCM_BIN = "./pcm.bin"
TARGET_PCM_ARRAY_FILE = "../../include/uni_pcm_array.h"
TARGET_PCM_DTAT_FILE = "../../include/pcm_bin.h"

ASRFIX_DAT = "./asrfix.dat"
TARGET_ASRFIX_DATA_FILE = "../../include/asrfix.h"

UNI_CONFIG = "./config.bin"
UNI_CONFIG_DEBUG = "./config_debug.bin"
UNI_CONFIG_RELEASE = "./config_release.bin"
TARGET_UNI_CONFIG_FILE = "../../include/config_bin.h"

GRAMMAR_DATA = "./grammar.dat"
TARGET_GRAMMAR_DATA_FILE = "../../include/grammar.h"

AIK_CONFIG = "./aik.json"
AIK_CONFIG_DEBUG = "./aik_debug.json"
AIK_CONFIG_RELEASE = "./aik_release.json"
TARGET_AIK_CONFIG_FILE = "../../include/aik-config.h"

CUSTOM_CONFIG_FILE = "./custom_config.json"
TARGET_CUST_CONFIG_H_FILE = "../../include/uni_cust_config.h"

CMD_CONTENT_FILE = "./cmd_reply_data.json"
TARGET_NUL_CONTENT_H_FILE = "../../include/uni_nlu_content.h"

CMD_CODE_START_NUM = 0x00
TARGET_SUCP_CONT_FILE = "./sucp_cmd_map.txt"
TARGET_CMD_CODE_H_FILE = "../../include/uni_cmd_code.h"

THRESH_DAT_FILE = "./thresh.dat"
ASR_THRESH_DAT_FILE = "./asr_thresh.dat"
'''


#--------  本py运行在tools/scripts 目录

REPLY_FILE = "./cmd_reply_data.json"
UART_DATA_FILE = "./uartCmd.json"
GPIO_CONFIG_FILE = "./custom_config.json"
GPIO_CONFIG_CODE_FILE = "../../user/src/examples/yfc_auto_gpio.c"
USER_CONFIG_H_FILE = "../../user/inc/user_config.h"

YFC_UART_HEAD = "#define UART_HEAT_1   (unsigned char)0x5a	  \n"
YFC_UART_TAIL = "#define UART_TAIL_1   (unsigned char)0xef	  \n"

#--------


'''
#串口接收
typedef struct{
	char data[UART_SEND_MAX];   //串口发送数组
	char len;				   //发送长度
	unsigned int addr;		  //语音指令序号
	code char *CmdName;		 //语音指令标识符
	code car *playList;		 //播报数组
}kpData;

const kpData g_uart_buf[] = {
   { { 0x5A, 0x00, 0x01, 0x6A, 0x01, 0x00, 0x00, 0xEF}, 8, 0x016A, "OpenLed"}, //OpenLed
};
'''

def _creat_include_code(code_file):
	code_file.write("#include \"user_config.h\"\n")
	code_file.write("#include \"user_event.h\"\n")
	code_file.write("#include \"user_gpio.h\"\n")
	code_file.write("#include \"user_player.h\"\n")
	code_file.write("#include \"user_pwm.h\"\n")
	code_file.write("#include \"user_timer.h\"\n")
	code_file.write("#include \"user_uart.h\"\n")
	code_file.write("\n")

def _creat_define_code(code_file):
	code_file.write("#define TAG \"auto_gpio\"\n")
	#define YFC_FW_VER		  "yfc firmware version : 20210227_V1.0.1 \\n"
	code_file.write("\n")
	code_file.write("#define YFC_FW_VER		  \"yfc firmware version : ")
	srcTime = time.strftime("%Y%m%d", time.localtime())
	print(srcTime)
	code_file.write(srcTime)
	code_file.write("_V1.0.0\\n\"\n")
	code_file.write("\n")	
	code_file.write("#define UART_SEND_MAX	  8\n")
	code_file.write(YFC_UART_HEAD)
	code_file.write(YFC_UART_TAIL)	
	code_file.write("\n")

def _creat_struct_code(code_file):
	code_file.write("typedef struct {\n")
	code_file.write("  char data[UART_SEND_MAX];	//串口发送数组\n")
	code_file.write("  unsigned char len;		   //发送长度\n")
	code_file.write("  unsigned int addr;		   //语音指令序号\n")
	code_file.write("  const char *CmdName;		  //语音指令标识符\n")
	code_file.write("  const char *playList;		  //\n")
	code_file.write("  const char *replyList;		  //\n")
	code_file.write("}yfcData;\n")
	code_file.write("\n")

def _creat_yfc_uart_buf_arry(code_file, uart_json, replyJson):
	code_file.write("const yfcData g_uart_buf[] = {\n")
	waitUpMaxWork = 0#唤醒词的个数
	waitUpMaxReplyWork = 0#唤醒词回复语的个数
	#wakeup
	for num in range(len(replyJson)):
		if replyJson[num]['cmd'] == "wakeup_uni":
			cmdBuf = replyJson[num]['pcm']
			cmdWord = replyJson[num]['cmd_word']
			break
	cmdReply ='['
	cmdFinish ='['
	waitUpMaxWork = len(cmdWord)
	waitUpMaxReplyWork = len(cmdBuf)
	for numCmd in range(len(cmdBuf)):
		if numCmd == 0:
			cmdFinish += str(cmdBuf[numCmd][0:3])		   #其他功能
			cmdReply += str(cmdBuf[numCmd][0:3])
		else:
			cmdFinish += ',' + str(cmdBuf[numCmd][0:3])
			cmdReply += ',' + str(cmdBuf[numCmd][0:3])
	cmdFinish += ']'
	cmdReply += ']'
	code_file.write("   {  {  0x5A, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0xEF}, 8, " + "0x0008, " + "\"wakeup_uni\"" + ", \"" + cmdFinish + "\"" + ", \"" + cmdReply + "\"" + "}, //wakeup_uni\n")
	
	#exituni
	exitCut = 0
	for num in range(len(replyJson)):
		if replyJson[num]['cmd'] == "exitUni":
			cmdBuf = replyJson[num]['pcm']
			exitCut = 1
			break
	if exitCut == 0:
		for num in range(len(replyJson)):
			if replyJson[num]['cmd'] == "asr_timeout_uni":
				cmdBuf = replyJson[num]['pcm']
				exitCut = 1
				break
	cmdReply ='['
	cmdFinish ='['
	for numCmd in range(len(cmdBuf)):
		if numCmd == 0:
			cmdFinish += str(cmdBuf[numCmd][0:3])		   #其他功能
			cmdReply += str(cmdBuf[numCmd][0:3])		   #
		else:
			cmdFinish += ',' + str(cmdBuf[numCmd][0:3])	 #
			cmdReply += ',' + str(cmdBuf[numCmd][0:3])		#
	cmdFinish += ']'
	cmdReply += ']'
	code_file.write("   {  {  0x5A, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00, 0xEF}, 8, " + "0x0009, " + "\"exitUni\"" + ", \"" + cmdFinish + "\"" + ", \"" + cmdReply + "\"" + "}, //exitUni\n")	
	
	count = 2
    #点击 双击 声效
	for pos in range(len(uart_json)):
		if uart_json[pos]['cmd'][0:5] == 'click':
			count += 1
			data = uart_json[pos]['uartData']
			data_split = data.split(', ')
			#print(data, data_split[0]) 
			action = uart_json[pos]['cmd']
			code_file.write("   {  { " + uart_json[pos]['uartData'] + "}, "  + str(8) + ", " + data_split[2] + data_split[3][2:] + ", \"" + action + "\"" + ", \"" + "[" + str(7) + "]" + "\"" + ", \"" + "[" + str(7) + "]" + "\"" + "}, //" + action + "\n")
		elif uart_json[pos]['cmd'][0:11] == 'doubleClick':
			count += 1
			data = uart_json[pos]['uartData']
			data_split = data.split(', ')
			#print(data, data_split[0]) 
			action = uart_json[pos]['cmd']
			code_file.write("   {  { " + uart_json[pos]['uartData'] + "}, "  + str(8) + ", " + data_split[2] + data_split[3][2:] + ", \"" + action + "\"" + ", \"" + "[" + str(8) + "]" + "\"" + ", \"" + "[" + str(8) + "]" + "\"" + "}, //" + action + "\n")

    #其他
	for num in range(len(replyJson)):
		cmdBuf = replyJson[num]['pcm']
		cmdReply ='['
		cmdFinish ='['
		for numCmd in range(len(cmdBuf)):
			if replyJson[num]['cmd'] == 'cmdTemp':
				if numCmd == 0:
					tempFrist = str(cmdBuf[numCmd][0:3])		   #转成字符串
				else:
					tempReply = str(cmdBuf[numCmd][0:3])	 #转成字符串
			elif replyJson[num]['cmd'] == 'cmdTime':
				if numCmd == 0:
					timeFrist = str(cmdBuf[numCmd][0:3])		   #转成字符串
				else:
					timeReply = str(cmdBuf[numCmd][0:3])	 #转成字符串
			else:
				if str(replyJson[num]['cmd'][0:3]) == 'tem':
					cmdFinish += tempFrist + ',' + str(cmdBuf[numCmd][0:3])	#
					cmdReply += tempReply + ',' + str(cmdBuf[numCmd][0:3])	 #				
				elif str(replyJson[num]['cmd'][0:3]) == 'tim':
					cmdFinish += timeFrist + ',' + str(cmdBuf[numCmd][0:3])	#
					cmdReply += timeReply + ',' + str(cmdBuf[numCmd][0:3])	 #				
				else:
					if numCmd == 0:
						cmdFinish += str(cmdBuf[numCmd][0:3])		   #其他功能
						cmdReply += str(cmdBuf[numCmd][0:3])		   #
					else:
						cmdFinish += ',' + str(cmdBuf[numCmd][0:3])	 #
						cmdReply += ',' + str(cmdBuf[numCmd][0:3])		#
		cmdFinish += ']'
		cmdReply += ']'

		for pos in range(len(uart_json)):
			if uart_json[pos]['cmd'] != 'cmdTemp' and uart_json[pos]['cmd'] != 'cmdTime':
				if replyJson[num]['cmd'] == uart_json[pos]['cmd']:
					count += 1
					data = uart_json[pos]['uartData']
					data_split = data.split(', ')
					#print(data, data_split[0]) 
					action = replyJson[num]['cmd']
					code_file.write("   {  { " + uart_json[pos]['uartData'] + "}, "  + str(8) + ", " + data_split[2] + data_split[3][2:] + ", \"" + action + "\"" + ", \"" + cmdFinish + "\"" + ", \"" + cmdReply + "\"" + "}, //" + action + "\n")
	
	#以下是只有回复语的
	replyNum = 500
	for pos in range(len(uart_json)):
		if uart_json[pos]['cmd'][0:6] == 'single':
			count += 1
			data = uart_json[pos]['uartData']
			data_split = data.split(', ')
			#print(data, data_split[0]) 
			action = uart_json[pos]['cmd']
			code_file.write("   {  { " + uart_json[pos]['uartData'] + "}, "  + str(8) + ", " + data_split[2] + data_split[3][2:] + ", \"" + action + "\"" + ", \"" + "[" + str(replyNum) + "]" + "\"" + ", \"" + "[" + str(replyNum) + "]" + "\"" + "}, //" + action + "\n")
			replyNum += 1
            
	code_file.write("};\n")
	code_file.write("\n")
	code_file.write("#define MAX_YFC_DATA			" + str(count) + "\n" )
	code_file.write("#define MAX_WAITUP_WORK		" + str(waitUpMaxWork) + "\n" )
	code_file.write("#define MAX_WAITUP_REPLT		" + str(waitUpMaxReplyWork) + "\n" )
	code_file.write("\n")

	#学习部分的全部播放列表
	code_file.write("const char *studyPlayList[] = { ")
	studyPlayListMax = 0
	studyPlayBuf = ""

	for num in range(len(reply_json)):
		print("get one\n")
		if reply_json[num]['cmd'] == "startStudy":
			cmdBuf = replyJson[num]['pcm']
			waitUpMaxReplyWork = len(cmdBuf)
			for numCmd in range(len(cmdBuf)):
				studyPlayListMax += 1
				studyPlayBuf += "\"" + str(cmdBuf[numCmd][0:3] + "\", ")
		if reply_json[num]['cmd'] == "clearStudy":
			cmdBuf = replyJson[num]['pcm']
			waitUpMaxReplyWork = len(cmdBuf)
			for numCmd in range(len(cmdBuf)):
				studyPlayListMax += 1
				studyPlayBuf += "\"" + str(cmdBuf[numCmd][0:3] + "\", ")
		if reply_json[num]['cmd'] == "startStuCmd":
			cmdBuf = replyJson[num]['pcm']
			waitUpMaxReplyWork = len(cmdBuf)
			for numCmd in range(len(cmdBuf)):
				studyPlayListMax += 1
				studyPlayBuf += "\"" + str(cmdBuf[numCmd][0:3] + "\", ")
		if reply_json[num]['cmd'] == "startStuWakeup":
			cmdBuf = replyJson[num]['pcm']
			waitUpMaxReplyWork = len(cmdBuf)
			for numCmd in range(len(cmdBuf)):
				studyPlayListMax += 1
				studyPlayBuf += "\"" + str(cmdBuf[numCmd][0:3] + "\", ")
		if reply_json[num]['cmd'] == "clearStuCmd":
			cmdBuf = replyJson[num]['pcm']
			waitUpMaxReplyWork = len(cmdBuf)
			for numCmd in range(len(cmdBuf)):
				studyPlayListMax += 1
				studyPlayBuf += "\"" + str(cmdBuf[numCmd][0:3] + "\", ")
		if reply_json[num]['cmd'] == "clearStuWakeup":
			cmdBuf = replyJson[num]['pcm']
			waitUpMaxReplyWork = len(cmdBuf)
			for numCmd in range(len(cmdBuf)):
				studyPlayListMax += 1
				studyPlayBuf += "\"" + str(cmdBuf[numCmd][0:3] + "\", ")
	code_file.write(studyPlayBuf)
	code_file.write('};\n')
	code_file.write('#define STUDY_PLAY_LIST	' + str(studyPlayListMax) + '\n')
	code_file.write('\n\n')

def _creat_yfc_cmd_work(code_file, reply_json):
	code_file.write("const char *waitUpCmdWork[] = { ")
	for num in range(len(reply_json)):
		if reply_json[num]['cmd'] == "wakeup_uni":
			strbuf = reply_json[num]['cmd_word']
			#print(strbuf)
			strListBuf = str(strbuf)
			strListBuf = str(strListBuf[1:-1])
			strListBuf = strListBuf.replace("\'", "\"")
			lastStr = ""
			for getStr in strListBuf:
				if getStr != ' ':
					lastStr += getStr
			print(lastStr)
			code_file.write(lastStr)
			break
	code_file.write('};\n')
	
	code_file.write("const char *exitCmdWork[] = { ")
	for num in range(len(reply_json)):
		if reply_json[num]['cmd'] == "exitUni":
			strbuf = reply_json[num]['cmd_word']
			#print(strbuf)
			strListBuf = str(strbuf)
			strListBuf = str(strListBuf[1:-1])
			strListBuf = strListBuf.replace("\'", "\"")
			print(strListBuf)
			code_file.write(strListBuf)
			break
	code_file.write('};\n')
	
	code_file.write("const char *volumeUpCmdWork[] = { ")
	for num in range(len(reply_json)):
		if reply_json[num]['cmd'] == "volumeUpUni":
			strbuf = reply_json[num]['cmd_word']
			#print(strbuf)
			strListBuf = str(strbuf)
			strListBuf = str(strListBuf[1:-1])
			strListBuf = strListBuf.replace("\'", "\"")
			print(strListBuf)
			code_file.write(strListBuf)
			break
	code_file.write('};\n')
	
	code_file.write("const char *volumeDownCmdWork[] = { ")
	for num in range(len(reply_json)):
		if reply_json[num]['cmd'] == "volumeDownUni":
			strbuf = reply_json[num]['cmd_word']
			#print(strbuf)
			strListBuf = str(strbuf)
			strListBuf = str(strListBuf[1:-1])
			strListBuf = strListBuf.replace("\'", "\"")
			print(strListBuf)
			code_file.write(strListBuf)
			break
	code_file.write('};\n')
	
	code_file.write("const char *volumeMaxCmdWork[] = { ")
	for num in range(len(reply_json)):
		if reply_json[num]['cmd'] == "volumeMaxUni":
			strbuf = reply_json[num]['cmd_word']
			#print(strbuf)
			strListBuf = str(strbuf)
			strListBuf = str(strListBuf[1:-1])
			strListBuf = strListBuf.replace("\'", "\"")
			print(strListBuf)
			code_file.write(strListBuf)
			break
	code_file.write('};\n')
	
	code_file.write("const char *volumeMinCmdWork[] = { ")
	for num in range(len(reply_json)):
		if reply_json[num]['cmd'] == "volumeMinUni":
			strbuf = reply_json[num]['cmd_word']
			#print(strbuf)
			strListBuf = str(strbuf)
			strListBuf = str(strListBuf[1:-1])
			strListBuf = strListBuf.replace("\'", "\"")
			print(strListBuf)
			code_file.write(strListBuf)
			break
	code_file.write('};\n')

	code_file.write("const char *volumeMidWork[] = { ")
	for num in range(len(reply_json)):
		if reply_json[num]['cmd'] == "volumeMidUni":
			strbuf = reply_json[num]['cmd_word']
			#print(strbuf)
			strListBuf = str(strbuf)
			strListBuf = str(strListBuf[1:-1])
			strListBuf = strListBuf.replace("\'", "\"")
			print(strListBuf)
			code_file.write(strListBuf)
			break
	code_file.write('};\n')
	
	code_file.write("const char *muteCleanCmdWork[] = { ")
	for num in range(len(reply_json)):
		if reply_json[num]['cmd'] == "muteClean":
			strbuf = reply_json[num]['cmd_word']
			#print(strbuf)
			strListBuf = str(strbuf)
			strListBuf = str(strListBuf[1:-1])
			strListBuf = strListBuf.replace("\'", "\"")
			print(strListBuf)
			code_file.write(strListBuf)
			break
	code_file.write('};\n')
	
	code_file.write("const char *muteSetWork[] = { ")
	for num in range(len(reply_json)):
		if reply_json[num]['cmd'] == "muteSet":
			strbuf = reply_json[num]['cmd_word']
			#print(strbuf)
			strListBuf = str(strbuf)
			strListBuf = str(strListBuf[1:-1])
			strListBuf = strListBuf.replace("\'", "\"")
			print(strListBuf)
			code_file.write(strListBuf)
			break
	code_file.write('};\n')


if __name__ == '__main__':
	global actionArray
	print("auto code start")
	code_file = open(GPIO_CONFIG_CODE_FILE, mode="w", encoding='utf-8', newline='\n')
	json_config_file = open(GPIO_CONFIG_FILE, mode="r", encoding='utf-8')
	json_reply_file = open(REPLY_FILE, mode="r", encoding='utf-8')	
	json_uart_file = open(UART_DATA_FILE, mode="r", encoding='utf-8')

	
	try:
		reply_json = json.load(json_reply_file)  
	except Exception as e:
		print('reply_config prase err:' + str(e))
		json_config_file.close()
		json_reply_file.close()

	try:
		uart_json = json.load(json_uart_file) 
	except Exception as e:
		print('uart_config prase err:' + str(e))
		json_config_file.close()
		json_reply_file.close()	 

	_creat_include_code(code_file)	  #加入头文件
	_creat_define_code(code_file)	   #加入宏定义
	_creat_struct_code(code_file)	   #加入结构体
	_creat_yfc_uart_buf_arry(code_file, uart_json, reply_json)#加入串口协议数组
	_creat_yfc_cmd_work(code_file, reply_json)

	json_reply_file.close()
	json_config_file.close()

	json_reply_file.close()
	json_config_file.close()
	code_file.close()

